package com.zyn.inventory.management.validator;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.zyn.inventory.management.forms.UserForm;
import com.zyn.inventory.management.services.UserService;

@Component
public class UserFormValidator implements Validator{
	@Resource
	private UserService userService;
	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";
	private static final String REAL_NAME = "realName";
	private static final String ROLE_IDS = "userRoles";
	public boolean supports(Class<?> clazz) {
		return UserForm.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		UserForm userForm = (UserForm)target;
		if(StringUtils.isBlank(userForm.getUsername()))
			errors.rejectValue(USERNAME, "user.username");
		if(StringUtils.isBlank(userForm.getPassword()))
			errors.rejectValue(PASSWORD, "user.password");
		if(StringUtils.isBlank(userForm.getRealName()))
			errors.rejectValue(REAL_NAME,"user.realname");
		if(userForm.getUserRoles()==null||userForm.getUserRoles().size()<1)
			errors.rejectValue(ROLE_IDS,"user.userRoles");
		
		if(userService.getByUsername(userForm.getUsername().trim())!=null)
			errors.rejectValue(USERNAME, "user.userExist",new String[]{userForm.getUsername()},"");
	}

}
